package com.bj58.analysis.tools.common;

/**
 * 
 */

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * 加密解密工具类
 * 
 * @author nicolas
 * 
 */
public class EncryptHelper {
	private static String strKey = "infolist", strParam = "queryivs";

	public static String desEncrypt(String source) throws Exception {
		if (source == null || source.length() == 0)
			return null;
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		DESKeySpec desKeySpec = new DESKeySpec(strKey.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(strParam.getBytes("UTF-8"));
		cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
		return StringHelper.toHexString(cipher.doFinal(source.getBytes("UTF-8"))).toUpperCase();
	}

	public static String desDecrypt(String source) throws Exception {
		if (source == null || source.length() == 0)
			return null;
		byte[] src = StringHelper.fromHexString(source);
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		DESKeySpec desKeySpec = new DESKeySpec(strKey.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(strParam.getBytes("UTF-8"));
		cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
		byte[] retByte = cipher.doFinal(src);
		return new String(retByte,"UTF-8");
	}

}
